package net.linlan.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import net.linlan.plat.comm.datasource.DynamicDataSource;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 *
 * Filename:DynamicDataSourceConfig.java
 * Desc:配置多数据源, 当数据库连接多个数据源时，需要在这个地方注入
 * 在注入之前，application.yml文件内信息必须配置正确
 *
 * @author Linlan
 * CreateTime:2017/9/28 18:23
 *
 * @version 1.0
 * @since 1.0
 */
@Configuration
public class DynamicDataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.druid.first")
    public DataSource firstDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.second")
    public DataSource secondDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource,
                                        DataSource secondDataSource
                                        ) {
        Map<String, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
        targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
        return new DynamicDataSource(firstDataSource, targetDataSources);
    }

    /**
     * 自动识别使用的数据库类型
     * 在mapper.xml中databaseId的值就是跟这里对应，
     * 如果没有databaseId选择则说明该sql适用所有数据库
     * @return databaseId provider
     */
    @Bean
    public DatabaseIdProvider getDatabaseIdProvider(){
        DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties properties = new Properties();
        properties.setProperty("Oracle","oracle");
        properties.setProperty("MySQL","mysql");
        properties.setProperty("DM8","dm8");
        properties.setProperty("DM DBMS","dm8");
//        properties.setProperty("DB2","db2");
//        properties.setProperty("MS-SQL","ms-sql");
//        properties.setProperty("PostgreSQL","postgresql");
//        properties.setProperty("Sybase","sybase");
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }
}
